package xhg.com.resell.base.httpbase;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 网络重试
 * @author lew1210
 */
public class RetryIntercepter implements Interceptor {
    /**
     * 最大重试次数
     */
    private int maxRetry;

    /**
     * 重试次数
     * 假如设置重试次数为3的话，则最大可能请求次数为4次(默认1次+ 重试3次）
     */
    private int retryNum;


    public RetryIntercepter(int maxRetry) {
        this.maxRetry = maxRetry;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryNum < maxRetry) {
            retryNum++;
            response = chain.proceed(request);
        }
        return response;
    }
}
